package cn.leon.content.service.impl;

import cn.leon.common.pojo.JsonUtils;
import cn.leon.common.pojo.TaotaoResult;
import cn.leon.content.service.ContentService;
import cn.leon.mapper.ContentMapper;
import cn.leon.pojo.Content;
import cn.leon.pojo.ContentExample;
import cn.leon.redis.JedisClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private ContentMapper contentMapper;

    @Autowired
    private JedisClient jedisClient;

    @Value("${CONTENT_KEY}")
    private String CONTENT_KEY;

    @Override
    public TaotaoResult addContent(Content content) {
        //补全content
        content.setCreated(new Date());
        content.setUpdated(new Date());
        //插入数据
        contentMapper.insert(content);
        //缓存同步 添加的时候把之前的cid的缓存删掉
        jedisClient.hdel(CONTENT_KEY,content.getCategoryId().toString());  //后面一个参数是获得id
        return TaotaoResult.ok();
    }

    @Override
    public List<Content> getContent(long cid) {
        try {
            //查询缓存
            String json = jedisClient.hget(CONTENT_KEY, cid + "");
            if (StringUtils.isNoneBlank(json)) {
                //把json转换成list
                List<Content> list = JsonUtils.jsonToList(json, Content.class);
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //根据cid查询内容列表
        ContentExample contentExample = new ContentExample();
        ContentExample.Criteria criteria = contentExample.createCriteria();
        criteria.andCategoryIdEqualTo(cid);
        List<Content> contentList = contentMapper.selectByExample(contentExample);
        //向缓存中添加数据
        try {
           jedisClient.hset(CONTENT_KEY,cid + "",JsonUtils.objectToJson(contentList));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contentList;
    }
}
